package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2022-08-23
 * Time: 21:56
 * name： 删除图书
 */
public class DelateOperation implements IOperation {
    //删除功能

    @Override
    public void way(BookList bookList) {
        System.out.println("请删除图书! ");
        System.out.println("请输入要删除得图书名字：");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        int index = -1;
        //遍历数组，寻找这本书并记录这本书所在位置
        for (int i = 0; i < bookList.getCountsize(); i++) {
            Book book = bookList.getpos(i);
            if (name.equals(book.getName())) {
                index = i;
                break;
            }
        }
        if(index == -1){
            System.out.println("系统中无此书！");
            return;
        }else {
            for (int i = index; i < bookList.getCountsize() ; i++) {
                //从后向前覆盖这本书
                //bookList[i] = bookList[i+1]    bookList 只是 BookList类
                // BookList类里面有一个 Book类得数组
                Book book = bookList.getpos(i+1);  // 先获取i+1位置得这本书
                bookList.setBooks(book,i);  // 将i+1 得book 设置为 i位置得book
            }
        }
        // 每次删除以后将最后一个位置腾出制空，防止内存泄露  （java中一个对象只有没人引用才会自动回收）
        bookList.setBooks(null, bookList.getCountsize()-1);
        // 删除以后，书架上得书减少一本
        bookList.setCountsize(bookList.getCountsize()-1);

        System.out.println("删除成功！");

    }
}
